<?php
session_start();
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';

// 简单的管理员验证（用户名为admin）
if (!isset($_SESSION['user_id']) || $_SESSION['username'] !== 'admin') {
    header('Location: login.php');
    exit;
}

// 获取统计数据
function getGameStats() {
    global $pdo;
    
    // 用户总数
    $stmt = $pdo->query("SELECT COUNT(*) as total_users FROM users");
    $total_users = $stmt->fetch()['total_users'];
    
    // 当前轮次
    $current_round = getCurrentRound();
    
    // 今日交易次数
    $stmt = $pdo->query("SELECT COUNT(*) as today_trades FROM transactions WHERE DATE(transaction_time) = CURDATE()");
    $today_trades = $stmt->fetch()['today_trades'];
    
    // 今日交易金额
    $stmt = $pdo->query("SELECT SUM(amount) as today_volume FROM transactions WHERE DATE(transaction_time) = CURDATE()");
    $today_volume = $stmt->fetch()['today_volume'] ?? 0;
    
    // 活跃用户（今日有交易）
    $stmt = $pdo->query("SELECT COUNT(DISTINCT user_id) as active_users FROM transactions WHERE DATE(transaction_time) = CURDATE()");
    $active_users = $stmt->fetch()['active_users'];
    
    return [
        'total_users' => $total_users,
        'current_round' => $current_round['round_number'],
        'today_trades' => $today_trades,
        'today_volume' => $today_volume,
        'active_users' => $active_users
    ];
}

$stats = getGameStats();

// 获取最近的交易记录
$stmt = $pdo->query("
    SELECT t.*, u.username, gr.round_number 
    FROM transactions t 
    JOIN users u ON t.user_id = u.id 
    JOIN game_rounds gr ON t.round_id = gr.id 
    ORDER BY t.transaction_time DESC 
    LIMIT 20
");
$recent_trades = $stmt->fetchAll();

// 获取用户列表
$stmt = $pdo->query("
    SELECT id, username, balance, frozen_profit, created_at,
           (SELECT COUNT(*) FROM transactions WHERE user_id = users.id) as trade_count
    FROM users 
    ORDER BY created_at DESC 
    LIMIT 50
");
$users = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理面板 - 投注游戏</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .admin-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stat-number {
            font-size: 28px;
            font-weight: bold;
            color: #4caf50;
            margin-bottom: 10px;
        }
        
        .stat-label {
            color: #666;
            font-size: 14px;
        }
        
        .admin-section {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .admin-section h2 {
            margin-bottom: 20px;
            color: #333;
            border-bottom: 2px solid #4caf50;
            padding-bottom: 10px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        th {
            background: #f8f9fa;
            font-weight: bold;
            color: #333;
        }
        
        tr:hover {
            background: #f5f5f5;
        }
        
        .trade-buy {
            color: #4caf50;
            font-weight: bold;
        }
        
        .trade-sell {
            color: #f44336;
            font-weight: bold;
        }
        
        .admin-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .admin-nav {
            display: flex;
            gap: 15px;
        }
        
        .admin-nav a {
            color: white;
            text-decoration: none;
            padding: 8px 15px;
            border-radius: 5px;
            background: rgba(255,255,255,0.2);
            transition: background 0.3s;
        }
        
        .admin-nav a:hover {
            background: rgba(255,255,255,0.3);
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <div class="admin-header">
            <div>
                <h1>投注游戏 - 管理面板</h1>
                <p>管理员：<?php echo htmlspecialchars($_SESSION['username']); ?></p>
            </div>
            <div class="admin-nav">
                <a href="index.php">返回游戏</a>
                <a href="admin_deposits.php">充值管理</a>
                <a href="admin_price_control.php">价格控制</a>
                <a href="#" onclick="refreshData()">刷新数据</a>
                <a href="logout.php">退出登录</a>
            </div>
        </div>
        
        <!-- 统计数据 -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['total_users']; ?></div>
                <div class="stat-label">总用户数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['current_round']; ?></div>
                <div class="stat-label">当前轮次</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">¥<?php echo number_format(getCurrentPrice(), 2); ?></div>
                <div class="stat-label">当前价格</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['today_trades']; ?></div>
                <div class="stat-label">今日交易次数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">¥<?php echo number_format($stats['today_volume'], 2); ?></div>
                <div class="stat-label">今日交易额</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['active_users']; ?></div>
                <div class="stat-label">今日活跃用户</div>
            </div>
        </div>
        
        <!-- 最近交易 -->
        <div class="admin-section">
            <h2>最近交易记录</h2>
            <table>
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>用户</th>
                        <th>轮次</th>
                        <th>类型</th>
                        <th>数量</th>
                        <th>价格</th>
                        <th>金额</th>
                        <th>盈亏</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recent_trades as $trade): ?>
                    <tr>
                        <td><?php echo date('m-d H:i:s', strtotime($trade['transaction_time'])); ?></td>
                        <td><?php echo htmlspecialchars($trade['username']); ?></td>
                        <td>第<?php echo $trade['round_number']; ?>轮</td>
                        <td class="trade-<?php echo $trade['type']; ?>">
                            <?php echo $trade['type'] === 'buy' ? '买入' : '卖出'; ?>
                        </td>
                        <td><?php echo number_format($trade['quantity'], 4); ?></td>
                        <td>¥<?php echo number_format($trade['price'], 2); ?></td>
                        <td>¥<?php echo number_format($trade['amount'], 2); ?></td>
                        <td style="color: <?php echo $trade['profit'] >= 0 ? '#4caf50' : '#f44336'; ?>">
                            ¥<?php echo number_format($trade['profit'], 2); ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- 用户列表 -->
        <div class="admin-section">
            <h2>用户列表</h2>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>余额</th>
                        <th>冻结盈利</th>
                        <th>交易次数</th>
                        <th>注册时间</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td><?php echo $user['id']; ?></td>
                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                        <td>¥<?php echo number_format($user['balance'], 2); ?></td>
                        <td>¥<?php echo number_format($user['frozen_profit'], 2); ?></td>
                        <td><?php echo $user['trade_count']; ?></td>
                        <td><?php echo date('Y-m-d H:i', strtotime($user['created_at'])); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <script>
        function refreshData() {
            location.reload();
        }
        
        // 每30秒自动刷新统计数据
        setInterval(function() {
            fetch('ajax/admin_stats.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.querySelector('.stats-grid .stat-card:nth-child(2) .stat-number').textContent = data.current_round;
                        document.querySelector('.stats-grid .stat-card:nth-child(3) .stat-number').textContent = '¥' + parseFloat(data.current_price).toLocaleString('zh-CN', {minimumFractionDigits: 2});
                        document.querySelector('.stats-grid .stat-card:nth-child(4) .stat-number').textContent = data.today_trades;
                        document.querySelector('.stats-grid .stat-card:nth-child(5) .stat-number').textContent = '¥' + parseFloat(data.today_volume).toLocaleString('zh-CN', {minimumFractionDigits: 2});
                        document.querySelector('.stats-grid .stat-card:nth-child(6) .stat-number').textContent = data.active_users;
                    }
                });
        }, 30000);
    </script>
</body>
</html>
